#!/usr/bin/python
import re
import time
import datetime
import ConfigParser
import sys
import os

configFile = "/etc/usagetracker.conf"

# Runs the "last" command and stores the output in a file specified by config
def generateLog():
    outputFile = open(configData["logfile"], "w")
    stdout_handle = os.popen("last -R |grep -v reboot", "r")
    text = stdout_handle.read()	
    outputFile.write(text)
    outputFile.close()

# Runs the "find" command to get all files accessed in given list of folders in last 1 month
def generateAccessLog():    
    if(configData.has_key("recentfiles") and configData.has_key("trackfolders")):
        outputFile = open(configData["recentfiles"], "w")
        trackFolders = map(str.strip, configData["trackfolders"].split(","))    
        outputFile.write("# access time: 1 month. folders: " + ", ".join(trackFolders) +"\n")
        for folder in trackFolders:        
            stdout_handle = os.popen("find " + folder +" -not -regex \".*/\..*\" -atime -30 -type f -printf \"%p%%%%%Aa, %Ab %Ad, %AH:%AM\n\"")
            text = stdout_handle.read()	
            outputFile.write(text)
        outputFile.close()

# Reads config info into a map from the given file.
# The file format should be one supported by the ConfigParser class
def getConfigData(filename):
    cfgData = {}
    cfgParser = ConfigParser.ConfigParser()
    cfgParser.read(filename)
    for (key, value) in cfgParser.items("TopLevel"):
	cfgData[key] = value
    return cfgData

# Parses the log file into a data structure
def parseLog():
    f = file(configData["logfile"])
    loginRecords = []

    for line in f:
        line = line.strip()
	rawData = line.split()
        data = map(str.strip,rawData)       
        if(len(data) > 0):
            if(" ".join(data[0:2]) != "wtmp begins"):                
                if(" ".join(data[6:9]) != "still logged in"):
                    loginRecord = {}	        
                    loginRecord["user"] = data[0]
                    loginRecord["date"] = " ".join(data[2:5])
                    loginRecord["startTime"] = data[5]
		    loginRecord["endTime"] = data[7]
		    loginRecord["duration"] = data[8]
                    loginRecords.append(loginRecord)

    datewiseLogins = {}
    #Get current year as the "last" command does not show it
    year = datetime.date.today().year

    #Sort the records by date
    for record in loginRecords:
        parsedDate = time.strptime(str(year)+" "+record["date"],"%Y %a %b %d")
        record["parsedDate"] = parsedDate
            
        if(str(int(time.mktime(parsedDate))) not in datewiseLogins):            
            datewiseLogins[str(int(time.mktime(parsedDate)))] = []

        datewiseLogins[str(int(time.mktime(parsedDate)))].append(record)

    return datewiseLogins

# Iterates over the login records and yields the next one
def getNextLoginRecord(datewiseLogins):
    dateKeys = datewiseLogins.keys()
    dateKeys.sort()
    for date in dateKeys:
        timestruct = time.localtime(float(date))
        for loginRecord in datewiseLogins[date]:
            yield (loginRecord, timestruct)

    
# Generates the report using the given data structure
def generateReport(datewiseLogins):
	#Redirect output to file if specified
	try:
		outputFile = open(configData["outputfile"], "w")
		sys.stdout = outputFile
	except:
		print "usagetracker: Error: No output file. Printing to stdout"

        print "Date                User          Start-Time           End-Time       Duration"
        print "------------------------------------------------------------------------------"
        for (loginRecord, timestruct) in getNextLoginRecord(datewiseLogins):
            print time.strftime("%a, %b %d, %Y",timestruct),"  ",loginRecord["user"],"     ",loginRecord["startTime"], "             ", loginRecord["endTime"], "          ",loginRecord["duration"]
            print
	
	#Reset stdout
	sys.stdout = sys.__stdout__

# Generates a HTML report using the given data structure
def generateHtmlReport(datewiseLogins):
      #Redirect output to file if specified
       try:
          outputFile = open(configData["outputhtmlfile"], "w")
	  sys.stdout = outputFile
       except:
	  print "usagetracker: Error: No output file. Printing to stdout"

       print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"
       print "<html>"
       print "<head>"
       print "<title>Usage Report - " + time.strftime("%a, %b %d, %Y",time.localtime()) +"</title>"
       print "<style type='text/css'>"
       print "    body{font-family: Verdana;}"
       print "</style>"
       print "</head>"
       print "<body>"
       print "<div><b>Usage Report - " + time.strftime("%a, %b %d, %Y",time.localtime()) +"</b></div>"
       print "<br/>"
       
       if(configData.has_key("recentfileshtml")):
           print "<div><a style='color:blue;' href='file://"+configData["recentfileshtml"]+"'>Recently Used Files</a></div>"
       print "<br/>"
       print "<table border='1' cellpadding='4'>"
       print "<tbody>"
       print "<tr>"
       print "<th>Date</th>"
       print "<th>User</th>"
       print "<th>Start-Time</th>"
       print "<th>End-Time</th>"
       print "<th>Duration<br/>(HH:MM)</th>"
       print "</tr>"
       for (loginRecord, timestruct) in getNextLoginRecord(datewiseLogins):
            print "<tr>"
            print "<td>",time.strftime("%a, %b %d, %Y",timestruct),"</td>"
            print "<td>",loginRecord["user"],"</td>"
            print "<td>",loginRecord["startTime"], "</td>"
            print "<td>",loginRecord["endTime"],"</td>"
            print "<td>",loginRecord["duration"],"</td>"
            print "</tr>"
       print "</tbody>"
       print "</table>"
       print "</body>"
       print "</html>"

       #Reset stdout
       sys.stdout = sys.__stdout__

# generates a HTML file with recently accessed files info
def generateAccessReport():
    #Redirect output to file if specified
    if(configData.has_key("recentfiles")):
        try:
            outputFile = open(configData["recentfileshtml"], "w")
	    sys.stdout = outputFile
        except:
	    print "usagetracker: Error: No output file for recent files. Printing to stdout"

        print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"
        print "<html>"
        print "<head>"
        print "<title>Recently Used Files - " + time.strftime("%a, %b %d, %Y",time.localtime()) +"</title>"
        print "<style type='text/css'>"
        print "    body{font-family: Verdana;}"
        print "</style>"
        print "</head>"
        print "<body>"
        print "<div><b>Recently Used Files - " + time.strftime("%a, %b %d, %Y",time.localtime()) +"</b></div>"
        print "<br/>"
        print "<table border='1' cellpadding='4'>"
        print "<tbody>"
        print "<tr>"
        print "<th>File name</th>"
        print "<th>Last used time</th>"
        print "</tr>"

        for line in file(configData["recentfiles"]):
            line = line.strip()
            if(line[0] != "#"):
                data = line.split("%%")
                print "<tr>"
                print "<td>"
                print data[0]
                print "</td>"
                print "<td>"
                print data[1]
                print "</td>"
                print "</tr>"
        print "</tbody>"
        print "</table>"
        print "</body>"
        print "</html>" 

# main()
configData = getConfigData(configFile)
generateLog()
datewiseLogins = parseLog()
generateReport(datewiseLogins)
generateHtmlReport(datewiseLogins)

generateAccessLog()
generateAccessReport()